<template>
  <view>
    <button @click="startRecording">开始录音</button>
    <button @click="stopRecording">停止录音</button>
    <canvas canvas-id="gauge" style="width: 300px; height: 300px;"></canvas>
  </view>
</template>

<script>
import { YIN } from 'pitchfinder';

export default {
  data() {
    return {
      recorderManager: null,
      audioContext: null,
      detector: null,
    };
  },
  methods: {
    startRecording() {
      this.recorderManager = wx.getRecorderManager();
      this.recorderManager.onFrameRecorded(this.processAudioFrame);
      this.recorderManager.start({
        format: 'pcm',
        frameSize: 1024
      });
    },
    stopRecording() {
      this.recorderManager.stop();
    },
    processAudioFrame(res) {
      const { frameBuffer } = res;
      const float32Array = new Float32Array(frameBuffer);
      const pitch = this.detector(float32Array);

      if (pitch) {
        this.drawGauge(pitch);
      }
    },
    drawGauge(pitch) {
      const ctx = wx.createCanvasContext('gauge');
      ctx.clearRect(0, 0, 300, 300);
      
      ctx.beginPath();
      ctx.arc(150, 150, 100, 0, 2 * Math.PI);
      ctx.stroke();

      const angle = (pitch / 1000) * 2 * Math.PI;
      ctx.beginPath();
      ctx.moveTo(150, 150);
      ctx.lineTo(150 + 100 * Math.cos(angle), 150 + 100 * Math.sin(angle));
      ctx.stroke();

      ctx.draw();
    }
  },
  mounted() {
    this.detector = YIN();
  }
};
</script>
